<?php

// Router to cache organisation names and read routes so we can have /organisationName

App::import('Core', 'Router');
App::import('Utility', 'ClassRegistry');

class OrganisationRoute extends CakeRoute {

    public function match($url) {

        if (!empty($url['organisationSlug']) && $this->_exists($url['organisationSlug'])) {
            return parent::match($url);
        }
        return false;
    }

    public function parse($url) {
        $params = parent::parse($url);
        if (!empty($params) && $this->_exists($params['organisationSlug'])) {
            return $params;
        }
        return false;
    }

    protected function _exists($organisationSlug) {
        $organisationSlugs = Cache::read('organisation_slugs');

        if (empty($organisationSlugs)) {
            $organisations = ClassRegistry::init('Organisation')->find('all', array(
                'fields' => 'slug',
                'recursive' => -1,
                'conditions' => array('active' => 1)
            ));

            if (!empty($organisations)) {
                $organisationSlugs = array_map(
                        'strtolower', Set::extract('/Organisation/slug', $organisations)
                );
                Cache::write('organisation_slugs', $organisationSlugs);
            }
        }

        return in_array($organisationSlug, (array) $organisationSlugs);
    }

}